package cn.wolfcode.p2p.base.service.impl;

import cn.wolfcode.p2p.base.exception.CustomerException;
import cn.wolfcode.p2p.base.service.IVerifyCodeService;
import cn.wolfcode.p2p.base.util.AssertUtil;
import cn.wolfcode.p2p.base.util.Constant;
import cn.wolfcode.p2p.base.util.HttpUtil;
import cn.wolfcode.p2p.base.util.LoginInfoContext;
import cn.wolfcode.p2p.base.vo.VerifyCodeVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
@Transactional
public class VerifyCodeServiceImpl implements IVerifyCodeService {

    @Value("${sms.httpUrl}")
    private String httpUrl;
    @Value("${sms.phone}")
    private String phone;
    @Value("${sms.content}")
    private String content;
    @Value("${sms.appKey}")
    private String appKey;
    @Value("${sms.appKeyValue}")
    private Object appKeyValue;


    @Override
    public void sendVerifyCode(String phoneNumber) {
        // 1 判断是否存在session, 如果存在, 判断是否在90s内, 如果在, 不重复发送
        VerifyCodeVO vo = LoginInfoContext.getVerifyCode();

        if (vo != null) {
            AssertUtil.INSTANCE.isSmaller(new Date(), vo.getSendTime(),
                    Constant.VERIFY_CODE_INTERVAL_SECOND, "短信发送太频繁");
        }

        // 2 获取UUID 的前四位 作为验证码
        String code = UUID.randomUUID().toString().substring(0, 4);

        // 3 发送短信验证码, 并在控制台打印
        System.out.println("验证码 : " + code);
        // 发送真正的验证码
        // 使用京东万象
        String httpURL = httpUrl + "?";
        Map<String, Object> params = new HashMap<>();
        params.put(phone, phoneNumber);
        params.put(content, "【叩丁狼】验证码为：" + code + ",欢迎注册平台！");
        params.put(appKey, appKeyValue);
        try {
            String responseText = HttpUtil.sendHttpRequest(httpURL, params);// 给短信网关发送请求, 发送短信
            System.out.println("responseText = " + responseText);
        } catch (Exception e){
            throw new CustomerException("短信服务器繁忙, 请稍后再试");
        }

        // 4 将手机号码, 验证码, 发送时间存储到session中
        LoginInfoContext.setVerifyCode(new VerifyCodeVO(phoneNumber, code, new Date()));
    }

    @Override
    public void checkCode(String username, String verifyCode) {

        VerifyCodeVO vo = LoginInfoContext.getVerifyCode();

        AssertUtil.INSTANCE.isNullObject(vo, "请发送验证码")
                .isEquals(vo.getPhoneNumber(), username, "手机号码请保持一致")
                .isEqualsIgnore(vo.getCode(), verifyCode, "验证码错误, 请重新输入")
                .isBigger(new Date(), vo.getSendTime(), Constant.VERIFY_CODE_VAILDATE_SECOND, "验证码已失效, 请重新发送短信验证码");

        // 验证成功, 清空session中的验证码信息
        LoginInfoContext.setVerifyCode(null);
    }
}
